<template>
  <div class="app-container">
    <div class="searchBox">
      <el-form :inline="true" :model="search" ref="searchForm">
        <el-form-item label="组名" prop="groupName">
          <el-input
            v-model="search.groupName"
            placeholder="请输入组名"
            clearable
            size="small"
            @keyup.enter.native="searchQuery"
          />
        </el-form-item>
        <el-form-item style="margin-top: -2px">
          <el-button type="primary" @click="searchQuery">查询</el-button>
          <el-button type="info" @click="search = {};searchQuery()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <qm-table
      ref="qmTable"
      keyProp="groupId"
      menuType="text"
      formRefs="groupForm"
      :isCustomForm="true"
      :data="query"
      :showView="false"
      :showCheckbox="false"
      :formOptions="{ labelWidth: '120px' }"
      :modalOptions="{ height: 630 }"
    >
      <qm-table-column field="groupName">组名</qm-table-column>
      <qm-table-column field="ruleId" :renderFunc="renderRule">引用规则</qm-table-column>

      <template v-slot:form="{ model, controlData, models }">
        <el-tabs style="height: 700px;">
          <el-tab-pane label="考勤组">
            <el-form
              class="qm-table-form"
              ref="groupForm"
              label-width="120px"
              :model="model"
              :rules="rules.groupForm"
            >

              <el-row>
                <el-col :span="12">
                  <el-form-item label="组名：" prop="groupName">
                    <el-input v-model="model.groupName" placeholder="请输入内容"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="考勤规则：" prop="ruleId">
                    <el-select v-model="model.ruleId" placeholder="请选择" :disabled="pageAction != 'create'">
                      <el-option
                        v-for="item in controlData.signRules"
                        :key="item.ruleId"
                        :label="item.ruleName"
                        :value="item.ruleId"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

            </el-form>
          </el-tab-pane>
          <el-tab-pane label="组内成员" v-if="pageAction === 'edit'">
            <div class="searchBox" style="margin-bottom: 10px;">
              <el-row>
                <el-col :span="6">
                  <el-select
                    v-model="searchUsers2"
                    value-key="value"
                    filterable
                    remote
                    placeholder="请输入关键词"
                    :remote-method="remoteMethod2"
                  >
                    <el-option
                      v-for="item in users2"
                      :key="item.userId"
                      :label="item.label"
                      :value="item"
                    ></el-option>
                  </el-select>
                </el-col>
                <el-col :span="2" :offset="1">
                  <el-button type="primary" @click="$refs['userTable'].fetchListData()">查询</el-button>
                </el-col>
                <el-col :span="2">
                  <el-button type="info" @click="searchUsers2 = null;$refs['userTable'].fetchListData()">重置</el-button>
                </el-col>
              </el-row>
            </div>

            <div class="searchBox">
              <el-row>
                <el-col :span="6">
                  <el-select
                    v-model="searchUsers"
                    value-key="value"
                    multiple
                    filterable
                    remote
                    placeholder="请输入关键词"
                    :remote-method="remoteMethod"
                  >
                    <el-option
                      v-for="item in users"
                      :key="item.userId"
                      :label="`${item.label}  (${item.loginId})`"
                      :value="item"
                    ></el-option>
                  </el-select>
                </el-col>
                <el-col :span="3" :offset="1">
                  <el-button type="primary" @click="addUsers">添加</el-button>
                </el-col>

                <el-col :span="6">
                  <el-cascader
                    v-model="departmentId"
                    clearable
                    placeholder="请选择部门"
                    :options="controlData.departments"
                    :show-all-levels="false"
                    :props="{value:'id', label:'text', checkStrictly:true}"
                  ></el-cascader>
                </el-col>
                <el-col :span="3" :offset="1">
                  <el-button type="primary" @click="batchAddUsers">批量添加</el-button>
                </el-col>
              </el-row>
            </div>

            <qm-table
              ref="userTable"
              keyProp="id"
              menuType="text"
              :urls="{query:'/eip/sign/groupUser/query', delete: '/eip/sign/groupUser/delete'}"
              :beforeQuery="groupUserBeforeQuery"
              :showCheckbox="false"
              :showEdit="false"
              :showToolbar="false"
            >
              <qm-table-column field="loginId">登录账号</qm-table-column>
              <qm-table-column field="userName">用户名</qm-table-column>
            </qm-table>
          </el-tab-pane>
        </el-tabs>
      </template>

    </qm-table>
  </div>
</template>

<script>
  import Controller from "@/libs/framework/controller";
  import request from "@/utils/request";

  export default class Instance extends Controller {
    onBeforeInit() {
      this.urls = {
        model: "/eip/sign/group/getListModel",
        query: "/eip/sign/group/query",
        save: "/eip/sign/group/save",
        delete: "/eip/sign/group/delete",
        entity: "/eip/sign/group/getEntity",
      }
    }

    onAfterGetEntity(result) {
      this.$data.row = result.models.model
      super.onAfterGetEntity(result);
    }

    mixin() {
      return {
        data() {
          return {
            row: {},
            searchUsers: [],
            searchUsers2: null,
            users: [],
            users2: [],
            departmentId: [],
            rules: {
              groupForm: {
                groupName: [{required: true, message: "组名不能为空", trigger: "blur"}],
                ruleId: [{required: true, message: "请选择考勤规则", trigger: "blur"}]
              }
            }
          };
        },
        methods: {
          renderRule(data, row, column) {
            let find = this.super.$util.find(
              this.controlData.signRules,
              (item) => {
                return item.ruleId === data;
              }
            );
            return (find || {}).ruleName;
          },
          groupUserBeforeQuery(params) {
            params.query.groupId = this.row.groupId;
            if (this.searchUsers2) {
              params.query.userId = this.searchUsers2.userId;
            }
            this.remoteMethod();
            this.remoteMethod2();
            this.searchUsers = [];
            this.searchUsers2 = null;
            this.departmentId = [];
          },
          remoteMethod(query) {
            request({
              url: "/admin/sysRole/setUsers/userSelect2",
              method: "get",
              params: {term: query},
            })
              .then((r) => {
                if (r && !r.initMessage) {
                  this.users = r.data.map((m) => {
                    return {
                      value: m.userId,
                      userId: m.userId,
                      label: m.userName,
                      loginId: m.loginId,
                      userName: m.userName,
                    };
                  });
                } else {
                  reject(r.initMessage || "数据请求失败");
                }
              })
              .catch((e) => {
                reject(e);
              });
          },
          remoteMethod2(query) {
            request({
              url: "/admin/sysRole/setUsers/userSelect2",
              method: "get",
              params: {term: query},
            })
              .then((r) => {
                if (r && !r.initMessage) {
                  this.users2 = r.data.map((m) => {
                    return {
                      value: m.userId,
                      userId: m.userId,
                      label: m.userName,
                      loginId: m.loginId,
                    };
                  });
                } else {
                  reject(r.initMessage || "数据请求失败");
                }
              })
              .catch((e) => {
                reject(e);
              });
          },
          addUsers() {
            if (null == this.searchUsers || this.searchUsers.length == 0) {
              this.$message("请先选择用户");
              return;
            }
            this.searchUsers.forEach((item) => {
              delete item.label;
              delete item.value;
            });
            request({
              url: "/eip/sign/groupUser/addUsers",
              method: "post",
              data: {
                groupId: this.row.groupId,
                users: this.searchUsers,
              },
            })
              .then((r) => {
                if (r && r.success) {
                  this.msgSuccess("添加成功")
                  //this.$message({
                  //  message: "添加成功",
                  //  type: "success",
                  //});
                  this.$refs["userTable"].refresh();
                } else {
                  this.msgError(r.message)
                  //this.$message({
                  //  message: r.message,
                  //  type: "error",
                  //});
                  this.searchUsers = [];
                  this.remoteMethod();
                }
              })
              .catch((e) => {
                reject(e);
              });
          },
          batchAddUsers() {
            if (null == this.departmentId || this.departmentId.length == 0) {
              this.$message("请先选择一个部门!");
              return;
            }
            let departmentId = this.departmentId[this.departmentId.length - 1];
            request({
              url: "/eip/sign/groupUser/addUsersByDept",
              method: "post",
              data: {
                departmentId: departmentId,
                groupId: this.row.groupId
              },
            })
              .then((r) => {
                if (r && r.success) {
                  this.msgSuccess("添加成功")
                } else {
                  this.msgError(r.message)
                }
              })
              .catch((e) => {
                reject(e);
              });
          }
        },
      };
    }
  };
</script>

<style scoped lang="scss">
</style>
